package com.jh.paymentchannel.util.yipiaolian;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtils {
	public static String sendPost(Map<String ,String> formData ,String url,String encoding)throws Exception {
		
		String requestString = getRequestParamString(formData,encoding);
		System.out.println(requestString);
		return sendPost(url ,requestString.getBytes(encoding) ,encoding);
	}
	
	public static String sendPost(String url,byte[] msg,String encoding)throws Exception {
    	URLConnection request = createRequest(url, "POST");

        OutputStream reqStream = request.getOutputStream();

        reqStream.write(msg);
        reqStream.close();

        ByteArrayOutputStream ms = new ByteArrayOutputStream();
    	InputStream resStream = request.getInputStream();
        
        byte[] buf = new byte[4096];
        int count,totalBytes = 0;
        
        while ((count = resStream.read(buf, 0, buf.length)) > 0) {
            ms.write(buf, 0, count);
            totalBytes += count;
        }
        resStream.close();
		return new String(ms.toByteArray(),encoding);
	}
	
	private static URLConnection createRequest(String strUrl, String strMethod) throws Exception {
    	URL url = new URL(strUrl);
    	URLConnection conn = url.openConnection();
    	conn.setDoInput(true);
    	conn.setDoOutput(true);
    	conn.setConnectTimeout(60000);  //设置连接主机超时（单位：毫秒）
    	conn.setReadTimeout(60000); 	//设置从主机读取数据超时（单位：毫秒）
    	if (conn instanceof HttpsURLConnection){
    		HttpsURLConnection httpsConn = (HttpsURLConnection)conn;
    		httpsConn.setRequestMethod(strMethod);
    		httpsConn.setSSLSocketFactory(SSLUtils.getInstance().getSSLSocketFactory());
    		httpsConn.setHostnameVerifier(simpleVerifier);
    	} else if (conn instanceof HttpURLConnection){
    		HttpURLConnection httpConn = (HttpURLConnection)conn;
    		httpConn.setRequestMethod(strMethod);
    	}
    	return conn;
    }

	private static final HostnameVerifier simpleVerifier = new HostnameVerifier() {
		public boolean verify(String arg0, SSLSession arg1) {
			return true;
		}
    };

    private static  String getRequestParamString(Map<String, String> requestParamsMap, String coder) {
    	StringBuffer params = new StringBuffer();
    	Iterator<Entry<String,String>> it = requestParamsMap.entrySet().iterator();
    	while (it.hasNext()) {
    	    Entry<String,String> element = it.next();
    	    params.append(element.getKey());  
    	    params.append("=");  
    	    params.append(element.getValue());  
    	    params.append("&");  
    	}  
    	if (params.length() > 0) {  
    	    params.deleteCharAt(params.length() - 1);  
    	}
    	return params.toString();
	}
}
